<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/26 0026
 * Time: 下午 12:51
 */
namespace app\admin\controller;

use app\common\Helper;
use app\common\validate\CaptchaValidate;
use think\captcha\Captcha;
use think\Controller;
use think\Exception;
use think\Request;

class Login extends Controller
{

    public function login(){
        $session_admin = session('ADMIN');
        if(!empty($session_admin->id)){
            $this->redirect('/index');
        }
        return $this->fetch();
    }

    public function doLogin(Request $request){
        if($this->request->isAjax()) {
            $param = $request->param();
            if(empty($param['username']) || empty($param['password'])){
                return show(config('status.error_code'),'用户名或密码不能为空','用户名或密码不能为空');
            }
            if(empty($param['captcha'])){
                return show(config('status.error_code'),'验证码不能为空','验证码不能为空');
            }
            try{
                (new CaptchaValidate())->goCheck();
            }catch(Exception $ex){
                return show(config('status.error_code'),'验证码不正确','验证码不正确');
            }
            $Operator = \app\admin\model\Operator::where('loginName',$param['username'])->find();
            if($Operator){
                if(Helper::passwordEncrypt($param['password']) == $Operator->password){
                    session('ADMIN', $Operator);
                    return show(config('status.success_code'),'ok','ok');
                }else{
                    return show(config('status.error_code'),'用户名或密码错误','用户名或密码错误');
                }
            }else{
                return show(config('status.error_code'),'用户名或密码错误','用户名或密码错误');
            }
        }
    }

    public function verify(){
        $captcha = new Captcha(config('captcha'));
        return $captcha->entry();
    }

    /**
     * Logout
     */
    public function logout(){
        session('ADMIN', null);

        // 清除浏览器 LocalStorage
        echo "<script>localStorage.clear();</script>";

        $this->redirect('/login');
    }

}